package xcmg.device.service.warehouse;

import com.github.pagehelper.PageInfo;
import yb.ecp.fast.infra.util.PageHelperPlus;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.agent.AgentAllotDO;
import xcmg.device.dao.entity.agent.AgentAllotDetailDO;
import xcmg.device.dao.entity.delivery.DeliveryNoteDO;
import xcmg.device.dao.entity.delivery.DeliveryReceiptMaterialDO;
import xcmg.device.dao.entity.threeGuaranteesPur.ThreeGuaranteesOutDO;
import xcmg.device.dao.entity.threeGuaranteesPur.ThreeGuaranteesOutDetailDO;
import xcmg.device.dao.entity.warehouse.WarehouseDeliveryDO;
import xcmg.device.dao.entity.warehouse.WarehouseDeliveryDetailDO;
import xcmg.device.dao.entity.warehouse.export.WarehouseDeliveryExportDO;
import xcmg.device.dao.mapper.PriMaterialsMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseDeliveryDetailMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseDeliveryMapper;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExportUtil;
import xcmg.device.infra.enums.BillDesc;
import xcmg.device.service.GenDocumentService;
import xcmg.device.service.vo.buyBack.BackInboundAddVO;
import xcmg.device.service.vo.buyBack.BackInboundDetailVO;
import xcmg.device.service.vo.buyBack.BackInboundVO;
import xcmg.device.service.vo.delivery.DeliveryNoteAddVO;
import xcmg.device.service.vo.delivery.DeliveryNoteDetailVO;
import xcmg.device.service.vo.delivery.DeliveryNoteVO;
import xcmg.device.service.vo.logistics.SendBillAddVO;
import xcmg.device.service.vo.logistics.SendBillDetailVO;
import xcmg.device.service.vo.logistics.SendBillVO;
import xcmg.device.service.vo.threeGuaranteesPur.ThreeGuaranteesOutAddVO;
import xcmg.device.service.vo.threeGuaranteesPur.ThreeGuaranteesOutDetailVO;
import xcmg.device.service.vo.threeGuaranteesPur.ThreeGuaranteesOutVO;
import xcmg.device.service.vo.warehouse.WarehouseDeliveryAddVO;
import xcmg.device.service.vo.warehouse.WarehouseDeliveryDetailVO;
import xcmg.device.service.vo.warehouse.WarehouseDeliveryVO;
import xcmg.device.service.vo.warehouse.allot.RegionAllotAddVO;
import xcmg.device.service.vo.warehouse.allot.RegionAllotDetailVO;
import xcmg.device.service.vo.warehouse.allot.RegionAllotVO;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.util.ListUtil;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class WarehouseDeliveryService {

    @Autowired
    private WarehouseDeliveryMapper warehouseDeliveryMapper;

    @Autowired
    private WarehouseDeliveryDetailMapper warehouseDeliveryDetailMapper;

    @Autowired
    private WarehouseDeliveryDetailService warehouseDeliveryDetailService;

    @Autowired
    private WarehouseDeliveryRecordService warehouseDeliveryRecordService;

    @Autowired
    private GenDocumentService genDocumentService;

    @Autowired
    private FastGenClient fastGenClient;

    @Autowired
    private CommonService commonService;

    @Autowired
    private HttpServletResponse response;
    @Autowired
    private PriMaterialsMapper priMaterialsMapper;
    /**
     * @Author: WangKe
     * @Description: 增加出库记录
     * @Date: 15:40 2018/1/17 0017
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode add(WarehouseDeliveryAddVO warehouseDeliveryAddVO, String userId, String orgId) throws Exception{
        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult.getCode() != ErrorCode.Success.getCode())
        {
            return ErrorCode.IllegalArument;
        }
        WarehouseDeliveryVO warehouseDeliveryVO = warehouseDeliveryAddVO.getHeaderInfo();
        warehouseDeliveryVO.setId(textResult.getValue());
        warehouseDeliveryVO.setDeliveryOrder(genDocumentService.getDocumentNo(BillDesc.OutputNo));
        warehouseDeliveryVO.setStatus(0);
        warehouseDeliveryVO.setCreateDate(new Date());
        warehouseDeliveryVO.setCreaterId(userId);
        warehouseDeliveryVO.setOrgId(orgId);
        warehouseDeliveryVO.setCreaterName(commonService.getUserName(userId));

        WarehouseDeliveryDO warehouseDeliveryDO = new WarehouseDeliveryDO();
        BeanUtils.copyProperties(warehouseDeliveryVO, warehouseDeliveryDO);
        boolean success = warehouseDeliveryMapper.insert(warehouseDeliveryDO)>0;

        //新增出库详情记录
        if(success){
            List<WarehouseDeliveryDetailVO> detailVOList = warehouseDeliveryAddVO.getDetailList();
            if(!ListUtil.isNullOrEmpty(detailVOList)){
                for(WarehouseDeliveryDetailVO detail : detailVOList){
                    detail.setDeliveryOrder(warehouseDeliveryVO.getDeliveryOrder());
                    detail.setOrgId(orgId);
                    detail.setCreaterId(userId);
                    detail.setCreaterName(warehouseDeliveryVO.getCreaterName());
                    success = warehouseDeliveryDetailService.add(detail).getCode()==0;
                    if(!success){
                        throw new Exception("新增出库详情记录失败");
                    }
                }
            }
        }
        ErrorCode code = success? ErrorCode.Success: ErrorCode.Failure;
        return code;
    }

    /**
     * @Author: WangKe
     * @Description: 更新相关记录
     * @Date: 15:10 2018/1/18 0018
     */
    public ErrorCode update(WarehouseDeliveryVO warehouseDeliveryVO){
        WarehouseDeliveryDO warehouseDeliveryDO = new WarehouseDeliveryDO();
        BeanUtils.copyProperties(warehouseDeliveryVO, warehouseDeliveryDO);
        return warehouseDeliveryMapper.updateByPrimaryKey(warehouseDeliveryDO)>0? ErrorCode.Success: ErrorCode.WarehouseIdError;
    }

    public boolean update(WarehouseDeliveryDO warehouseDeliveryDO){
        return warehouseDeliveryMapper.updateByPrimaryKey(warehouseDeliveryDO)>0;
    }

    /**
     * @Author: WangKe
     * @Description: 根据主键删除出库记录
     * @Date: 15:40 2018/1/17 0017
     */
    public ErrorCode delete(List<String> ids, String orgId){
        if(ids.size()<=0){
            return ErrorCode.IllegalArument;
        }
        List<String> orderList = warehouseDeliveryMapper.findOrderList(ids);
        if(ListUtil.isNullOrEmpty(orderList)){
            return ErrorCode.IllegalArument;
        }
        boolean success = warehouseDeliveryMapper.remove(ids)>0;
        //删除入库详情记录
        if(success){
            warehouseDeliveryDetailService.deleteByDeliveryOrderList(orderList, orgId);
            warehouseDeliveryRecordService.deleteByDeliveryOrderList(orderList, orgId);
        }
        return success? ErrorCode.Success: ErrorCode.WarehouseIdError;
    }

    /**
     * @Author: WangKe
     * @Description: 根据业务单号删除事务单
     * @Date: 2018/3/8 0008
     */
    public ErrorCode removeByBusinessOrders(List<String> businessOrders, String orgId){
        if(ListUtil.isNullOrEmpty(businessOrders)){
            return ErrorCode.IllegalArument;
        }
        return this.delete(warehouseDeliveryMapper.findIdsByBusinessOrders(businessOrders, orgId), orgId);
    }

    /**
     * @Author: WangKe
     * @Description: 查找出库记录列表
     * @Date: 15:44 2018/1/17 0017
     */
    public PageCommonVO list(SearchCommonVO<WarehouseDeliveryVO> condition) {
        PageCommonVO<WarehouseDeliveryVO> pageCommonVO = new PageCommonVO();
        PageHelperPlus.orderBy("create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<WarehouseDeliveryDO> doList = warehouseDeliveryMapper.list(condition.getFilters());
        List<WarehouseDeliveryVO> voList = new ArrayList<WarehouseDeliveryVO>();
        for (WarehouseDeliveryDO entity : doList) {
            WarehouseDeliveryVO model = new WarehouseDeliveryVO();
            BeanUtils.copyProperties(entity, model);
            voList.add(model);
        }
        pageCommonVO.setPageInfo(new PageInfo(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    public List<WarehouseDeliveryDO> findList(WarehouseDeliveryVO vo){
        return warehouseDeliveryMapper.list(vo);
    }

    /**
     * @Author: WangKe
     * @Description: 根据主键查找实体
     * @Date: 2018/1/19 0019
     */
    public WarehouseDeliveryAddVO findByPK(String id){
        WarehouseDeliveryAddVO model = new WarehouseDeliveryAddVO();
        WarehouseDeliveryDO entity = warehouseDeliveryMapper.selectByPrimaryKey(id);
        if(entity == null){
            return null;
        }
        WarehouseDeliveryDetailVO vo = new WarehouseDeliveryDetailVO();
        vo.setDeliveryOrder(entity.getDeliveryOrder());
        vo.setOrgId(entity.getOrgId());
        List<WarehouseDeliveryDetailDO> doList = warehouseDeliveryDetailService.findListByCondition(vo);

        List<WarehouseDeliveryDetailVO> voList = new ArrayList<WarehouseDeliveryDetailVO>();
        if(org.apache.commons.collections.CollectionUtils.isNotEmpty(doList)){
            WarehouseDeliveryDetailVO warehouseDeliveryDetailVO = null;
            for(WarehouseDeliveryDetailDO m:doList){
                warehouseDeliveryDetailVO = new WarehouseDeliveryDetailVO();
                BeanUtils.copyProperties(m, warehouseDeliveryDetailVO);
                voList.add(warehouseDeliveryDetailVO);
            }
        }
        WarehouseDeliveryVO warehouseDeliveryVO = new WarehouseDeliveryVO();
        BeanUtils.copyProperties(entity, warehouseDeliveryVO);

        model.setHeaderInfo(warehouseDeliveryVO);
        model.setDetailList(voList);
        return model;
    }

    /**
     * @Author: WangKe
     * @Description: 导出出库数据列表信息
     * @Date: 2018/2/7 0007
     */
    public void export(List<String> ids)throws Exception{
        invokeExport(warehouseDeliveryMapper.findListForExport(ids));
    }

    /**
     * @Author: WangKe
     * @Description:
     * @Date: 2018/2/7 0007
     */
    public void exportAll(WarehouseDeliveryVO condition)throws Exception{
        Integer count = warehouseDeliveryMapper.findCountForExportAll(condition);
        List<WarehouseDeliveryExportDO> dataList = new ArrayList<>();
        int times = count/500+1;
        for(int i=0; i<times; i++){
            PageHelperPlus.startPage(i + 1, 500, "create_date desc");
            dataList.addAll(warehouseDeliveryMapper.findListForExportAll(condition));
        }
        invokeExport(dataList);
    }


    /**
     * @Author: WangKe
     * @Description: 导出出库数据列表信息
     * @Date: 2018/2/7 0007
     */
    private void invokeExport(List<WarehouseDeliveryExportDO> doList)throws Exception{
        if(ListUtil.isNullOrEmpty(doList)){
            return;
        }
        String title = "出库数据导出";
        String[] rowsName = new String[]{"序号","出库单号","业务类别","业务单号","仓库编码",
                "备注信息","零件编码", "零件名称", "零件类型", "拟出库数量", "实际出库数量", "单位", "出库状态",
                "制单人", "制单日期"};
        List<Object[]>  dataList = new ArrayList<Object[]>();
        Object[] objs;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < doList.size(); i++) {
            WarehouseDeliveryExportDO deliveryExportDO = doList.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i+1;
            objs[1] = deliveryExportDO.getDeliveryOrder();
            objs[2] = deliveryExportDO.getBusinessSingle();
            objs[3] = deliveryExportDO.getBusinessOrder();
            objs[4] = deliveryExportDO.getWarehouseCode();
            objs[5] = deliveryExportDO.getNote();
            objs[6] = deliveryExportDO.getMaterialNo();
            objs[7] = deliveryExportDO.getMaterialName();
            objs[8] = deliveryExportDO.getMaterialType();
            objs[9] = deliveryExportDO.getAmount();
            objs[10] = deliveryExportDO.getRealAmount();
            objs[11] = deliveryExportDO.getUnit();
            objs[12] = getState(deliveryExportDO.getStatus());
            objs[13] = deliveryExportDO.getCreaterName();
            objs[14] = sdf.format(deliveryExportDO.getCreateDate());
            dataList.add(objs);
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

    private String getState(Integer state){
        if(state == null){
            state = 0;
        }
        if(state == 0){
            return "未完成";
        }else if(state == 1){
            return "部分完成";
        }else{
            return "已完成";
        }
    }

    /**
     * @Author: WangKe
     * @Description: 在新增区域调拨单时生成出库单
     * @Date: 2018/2/11 0011
     */
    public boolean saveByRegionAllotOut(RegionAllotAddVO regionAllotAddVO, String userId, String orgId) throws Exception{
        if(regionAllotAddVO == null){
            return false;
        }
        RegionAllotVO allotVO = regionAllotAddVO.getHeaderInfo();
        List<RegionAllotDetailVO> detailVOList = regionAllotAddVO.getDetailList();

        WarehouseDeliveryVO deliveryVO = new WarehouseDeliveryVO();
        List<WarehouseDeliveryDetailVO> detailList = new ArrayList<WarehouseDeliveryDetailVO>();
        deliveryVO.setBusinessSingle(allotVO.getAllotOrder().substring(0, 4));
        deliveryVO.setBusinessOrder(allotVO.getAllotOrder());
        deliveryVO.setWarehouseCode(allotVO.getOutLocation());
        deliveryVO.setOutArea(allotVO.getOutArea());
        deliveryVO.setSapOutArea(allotVO.getSapOutArea());

        BigDecimal num = BigDecimal.ZERO;
        if(ListUtil.isNullOrEmpty(detailVOList)){
            return false;
        }
        WarehouseDeliveryDetailVO detail;
        for(RegionAllotDetailVO allotDetailVO : detailVOList){
            detail = new WarehouseDeliveryDetailVO();
            detail.setBusinessSingle(deliveryVO.getBusinessSingle());
            detail.setBusinessOrder(deliveryVO.getBusinessOrder());
            detail.setMaterialNo(allotDetailVO.getMaterialNo());
            detail.setMaterialName(allotDetailVO.getMaterialName());
            detail.setMaterialType(allotDetailVO.getMaterialType());
            detail.setUnit(allotDetailVO.getUnit());
            detail.setAmount(allotDetailVO.getAmount());
            detail.setRealAmount(BigDecimal.ZERO);

            num = num.add(allotDetailVO.getAmount());
            detailList.add(detail);
        }
        deliveryVO.setAmount(num);
        WarehouseDeliveryAddVO DeliveryAddVO = new WarehouseDeliveryAddVO();
        DeliveryAddVO.setHeaderInfo(deliveryVO);
        DeliveryAddVO.setDetailList(detailList);

        ErrorCode code = this.add(DeliveryAddVO, userId, orgId);
        return code.getCode() == 0;
    }

    /**
     * @Author: WangKe
     * @Description: 在生成三包出库单时生成出库事物单
     * @Date: 2018/3/13 0013
     */
    public boolean saveByThreeGuaranteesOut(ThreeGuaranteesOutAddVO threeGuaranteesOutAddVO, String userId, String orgId) throws Exception{
        if(threeGuaranteesOutAddVO == null){
            return false;
        }
        ThreeGuaranteesOutVO threeVO = threeGuaranteesOutAddVO.getHeaderInfo();
        List<ThreeGuaranteesOutDetailVO> detailVOList = threeGuaranteesOutAddVO.getDetailList();

        WarehouseDeliveryVO deliveryVO = new WarehouseDeliveryVO();
        List<WarehouseDeliveryDetailVO> detailList = new ArrayList<WarehouseDeliveryDetailVO>();
        deliveryVO.setBusinessSingle(threeVO.getGuaranteesOutNo().substring(0, 4));
        deliveryVO.setBusinessOrder(threeVO.getGuaranteesOutNo());
        deliveryVO.setWarehouseCode(threeVO.getOutLocation());
        deliveryVO.setOutArea(threeVO.getOutArea());
        deliveryVO.setSapOutArea(threeVO.getSapOutArea());

        BigDecimal num = BigDecimal.ZERO;
        if(ListUtil.isNullOrEmpty(detailVOList)){
            return false;
        }
        WarehouseDeliveryDetailVO detail;
        for(ThreeGuaranteesOutDetailVO detailVO : detailVOList){
            if(detailVO.getDeliveryQty() == null ){
                continue;
            }
            detail = new WarehouseDeliveryDetailVO();
            detail.setBusinessSingle(deliveryVO.getBusinessSingle());
            detail.setBusinessOrder(deliveryVO.getBusinessOrder());
            detail.setMaterialNo(detailVO.getMaterialsNo());
            detail.setMaterialName(detailVO.getMaterialsDesc());
            detail.setMaterialType(detailVO.getMaterialsType());
            detail.setUnit(detailVO.getUnit());
            detail.setAmount(detailVO.getDeliveryQty());
            detail.setRealAmount(BigDecimal.ZERO);

            num = num.add(detailVO.getDeliveryQty());
            detailList.add(detail);
        }
        deliveryVO.setAmount(num);
        WarehouseDeliveryAddVO DeliveryAddVO = new WarehouseDeliveryAddVO();
        DeliveryAddVO.setHeaderInfo(deliveryVO);
        DeliveryAddVO.setDetailList(detailList);

        ErrorCode code = this.add(DeliveryAddVO, userId, orgId);
        return code.getCode() == 0;
    }

    /**
     * @Des 随车自动创建出库单时新增出库事务单
     * @Date 2021/1/21 10:11
     * @Author wangzhaoyu
     * @Param [threeGuaranteesOutDO, details, userId, orgId]
     * @Return boolean
     */
    public boolean saveScThreeOutWarehouseDelivery(ThreeGuaranteesOutDO threeGuaranteesOutDO , List<ThreeGuaranteesOutDetailDO> details, String orgId) throws Exception{

        WarehouseDeliveryVO deliveryVO = new WarehouseDeliveryVO();
        List<WarehouseDeliveryDetailVO> detailList = new ArrayList<WarehouseDeliveryDetailVO>();
        deliveryVO.setBusinessSingle(threeGuaranteesOutDO.getGuaranteesOutNo().substring(0, 4));
        deliveryVO.setBusinessOrder(threeGuaranteesOutDO.getGuaranteesOutNo());
        deliveryVO.setWarehouseCode(threeGuaranteesOutDO.getOutLocation());
        deliveryVO.setOutArea(threeGuaranteesOutDO.getOutArea());
        deliveryVO.setSapOutArea(threeGuaranteesOutDO.getSapOutArea());

        BigDecimal num = BigDecimal.ZERO;
        if(ListUtil.isNullOrEmpty(details)){
            return false;
        }
        WarehouseDeliveryDetailVO detail;
        for(ThreeGuaranteesOutDetailDO outDetail : details){
            if(outDetail.getDeliveryQty() == null ){
                continue;
            }
            detail = new WarehouseDeliveryDetailVO();
            detail.setBusinessSingle(deliveryVO.getBusinessSingle());
            detail.setBusinessOrder(deliveryVO.getBusinessOrder());
            detail.setMaterialNo(outDetail.getMaterialsNo());
            detail.setMaterialName(outDetail.getMaterialsDesc());
            detail.setMaterialType(outDetail.getMaterialsType());
            detail.setUnit(outDetail.getUnit());
            detail.setAmount(outDetail.getDeliveryQty());
            detail.setRealAmount(BigDecimal.ZERO);

            num = num.add(outDetail.getDeliveryQty());
            detailList.add(detail);
        }
        deliveryVO.setAmount(num);
        WarehouseDeliveryAddVO DeliveryAddVO = new WarehouseDeliveryAddVO();
        DeliveryAddVO.setHeaderInfo(deliveryVO);
        DeliveryAddVO.setDetailList(detailList);

        ErrorCode code = this.add(DeliveryAddVO, threeGuaranteesOutDO.getCreateId(), orgId);
        return code.getCode() == 0;
    }

    /**
     * @Author: WangKe
     * @Description: 在代理商间调拨单调出审核通过时生成出库单
     * @Date: 2018/2/27 0027
     */
    public boolean saveByAgentAllotOut(AgentAllotDO agentAllotDO, List<AgentAllotDetailDO> detailVOList,
                                       String userId, String orgId) throws Exception{
        if(agentAllotDO == null || ListUtil.isNullOrEmpty(detailVOList)){
            return false;
        }
        WarehouseDeliveryVO deliveryVO = new WarehouseDeliveryVO();
        List<WarehouseDeliveryDetailVO> detailList = new ArrayList<WarehouseDeliveryDetailVO>();
        deliveryVO.setBusinessSingle(agentAllotDO.getAllotOrder().substring(0, 4));
        deliveryVO.setBusinessOrder(agentAllotDO.getAllotOrder());
        deliveryVO.setOutArea(agentAllotDO.getOutArea());
        deliveryVO.setSapOutArea(agentAllotDO.getSapOutArea());

        BigDecimal num = BigDecimal.ZERO;
        WarehouseDeliveryDetailVO detail;
        for(AgentAllotDetailDO allotDetailDO : detailVOList){
            detail = new WarehouseDeliveryDetailVO();
            detail.setBusinessSingle(deliveryVO.getBusinessSingle());
            detail.setBusinessOrder(deliveryVO.getBusinessOrder());
            detail.setMaterialNo(allotDetailDO.getMaterialNo());
            detail.setMaterialName(allotDetailDO.getMaterialName());
            detail.setMaterialType(allotDetailDO.getMaterialType());
            detail.setUnit(allotDetailDO.getUnit());
            detail.setAmount(allotDetailDO.getAmount());
            detail.setRealAmount(BigDecimal.ZERO);

            num = num.add(allotDetailDO.getAmount());
            detailList.add(detail);
        }
        deliveryVO.setAmount(num);
        WarehouseDeliveryAddVO DeliveryAddVO = new WarehouseDeliveryAddVO();
        DeliveryAddVO.setHeaderInfo(deliveryVO);
        DeliveryAddVO.setDetailList(detailList);

        ErrorCode code = this.add(DeliveryAddVO, userId, orgId);
        return code.getCode() == 0;
    }

    /**
     * @Author: WangKe
     * @Description: 新增发货通知单时新增发货事物单
     * @Date: 2018/3/21 0021
     */
    public boolean saveByDeliveryNoteOut(DeliveryNoteAddVO deliveryNoteAddVO, String userId, String orgId) throws Exception{
        if(deliveryNoteAddVO == null){
            return false;
        }
        DeliveryNoteVO deliveryNoteVO = deliveryNoteAddVO.getHeaderInfo();
        List<DeliveryNoteDetailVO> noteDetailVOList = deliveryNoteAddVO.getMaterialList();

        WarehouseDeliveryVO deliveryVO = new WarehouseDeliveryVO();
        List<WarehouseDeliveryDetailVO> detailList = new ArrayList<>();
        deliveryVO.setBusinessSingle(deliveryNoteVO.getDeliveryNo().substring(0, 4));
        deliveryVO.setBusinessOrder(deliveryNoteVO.getDeliveryNo());
        deliveryVO.setWarehouseCode(deliveryNoteVO.getOutLocation());
        deliveryVO.setOutArea(deliveryNoteVO.getOutArea());
        deliveryVO.setSapOutArea(deliveryNoteVO.getSapOutArea());

        BigDecimal num = BigDecimal.ZERO;
        WarehouseDeliveryDetailVO detail;
        for(DeliveryNoteDetailVO noteDetailDO : noteDetailVOList){
            detail = new WarehouseDeliveryDetailVO();
            detail.setBusinessSingle(deliveryVO.getBusinessSingle());
            detail.setBusinessOrder(deliveryVO.getBusinessOrder());
            detail.setMaterialNo(noteDetailDO.getMaterialsNo());
            detail.setMaterialName(noteDetailDO.getMaterialsDes());
            detail.setUnit(noteDetailDO.getUnit());
            detail.setAmount(noteDetailDO.getDeliveryQty());
            detail.setRealAmount(BigDecimal.ZERO);

            num = num.add(detail.getAmount());
            detailList.add(detail);
        }
        deliveryVO.setAmount(num);
        WarehouseDeliveryAddVO DeliveryAddVO = new WarehouseDeliveryAddVO();
        DeliveryAddVO.setHeaderInfo(deliveryVO);
        DeliveryAddVO.setDetailList(detailList);

        ErrorCode code = this.add(DeliveryAddVO, userId, orgId);
        return code.getCode() == 0;
    }

    /**
     * @Author: WangKe
     * @Description: 新增发运交接单时新增发货事物单
     * @Date: 2018/11/5 0005
     */
    public boolean saveByDeliveryReceipt(String receiptNo, List<DeliveryReceiptMaterialDO> list, String userId, String orgId) throws Exception{
        WarehouseDeliveryVO deliveryVO = new WarehouseDeliveryVO();
        List<WarehouseDeliveryDetailVO> detailList = new ArrayList<>();
        deliveryVO.setBusinessSingle(receiptNo.substring(0, 4));
        deliveryVO.setBusinessOrder(receiptNo);

        BigDecimal num = BigDecimal.ZERO;
        WarehouseDeliveryDetailVO detail;
        for(DeliveryReceiptMaterialDO materialDO : list){
            detail = new WarehouseDeliveryDetailVO();
            detail.setBusinessSingle(deliveryVO.getBusinessSingle());
            detail.setBusinessOrder(deliveryVO.getBusinessOrder());
            detail.setMaterialNo(materialDO.getMaterialsNo());
            detail.setMaterialName(materialDO.getMaterialsDes());
            detail.setUnit(materialDO.getUnit());
            detail.setAmount(materialDO.getQty());
            detail.setRealAmount(materialDO.getOutQty()==null?BigDecimal.ZERO:materialDO.getOutQty());
            detail.setStatus(materialDO.getOutStatus());

            num = num.add(detail.getAmount());
            detailList.add(detail);
        }
        deliveryVO.setAmount(num);
        WarehouseDeliveryAddVO DeliveryAddVO = new WarehouseDeliveryAddVO();
        DeliveryAddVO.setHeaderInfo(deliveryVO);
        DeliveryAddVO.setDetailList(detailList);

        ErrorCode code = this.add(DeliveryAddVO, userId, orgId);
        return code.getCode() == 0;
    }


    /**
    * @Desc   送货单提交时新增出库事物单
    * @Author Mr.dong
    * @Date   2021/9/7 18:26
    */
    public boolean saveBySendBillOut(SendBillAddVO sendBillAddVO, String userId, String orgId) throws Exception{
        if(sendBillAddVO == null){
            return false;
        }
        SendBillVO sendBillVO = sendBillAddVO.getHeaderInfo();
        List<SendBillDetailVO> detailVOList = sendBillAddVO.getMaterialsList();

        WarehouseDeliveryVO deliveryVO = new WarehouseDeliveryVO();
        List<WarehouseDeliveryDetailVO> detailList = new ArrayList<>();
        deliveryVO.setBusinessSingle(sendBillVO.getSendOrder().substring(0, 4));
        deliveryVO.setBusinessOrder(sendBillVO.getSendOrder());

        BigDecimal num = BigDecimal.ZERO;
        WarehouseDeliveryDetailVO detail;
        for(SendBillDetailVO detailVO : detailVOList){
            detail = new WarehouseDeliveryDetailVO();
            detail.setBusinessSingle(deliveryVO.getBusinessSingle());
            detail.setBusinessOrder(deliveryVO.getBusinessOrder());
            detail.setMaterialNo(detailVO.getMaterialsNo());
            detail.setMaterialName(detailVO.getMaterialsDes());
            detail.setUnit(detailVO.getUnit());
            detail.setAmount(detailVO.getQty());
            detail.setRealAmount(BigDecimal.ZERO);

            num = num.add(detail.getAmount());
            detailList.add(detail);
        }
        deliveryVO.setAmount(num);
        WarehouseDeliveryAddVO addVO = new WarehouseDeliveryAddVO();
        addVO.setHeaderInfo(deliveryVO);
        addVO.setDetailList(detailList);

        ErrorCode code = this.add(addVO, userId, orgId);
        return code.getCode() == 0;
    }

    /**
     * @Author: WangKe
     * @Description: 更新出库详情记录状态
     * @Date: 2018/3/8 0008
     */
    public ErrorCode updateDetailState(String businessOrder, String materialNo, BigDecimal amount, Integer state, String orgId){
        WarehouseDeliveryDetailVO inboundDetailVO = new WarehouseDeliveryDetailVO();
        inboundDetailVO.setBusinessOrder(businessOrder);
        inboundDetailVO.setMaterialNo(materialNo);
        inboundDetailVO.setOrgId(orgId);
        List<WarehouseDeliveryDetailDO> inboundDetailList = warehouseDeliveryDetailMapper.list(inboundDetailVO);
        if(ListUtil.isNullOrEmpty(inboundDetailList)){
            return ErrorCode.IllegalArument;
        }
        WarehouseDeliveryDetailDO inboundDetailDO = inboundDetailList.get(0);
        if (null != amount)
        {
            inboundDetailDO.setAmount(amount);
        }
        inboundDetailDO.setStatus(state);

        return warehouseDeliveryDetailMapper.updateByPrimaryKey(inboundDetailDO)>0?ErrorCode.Success:ErrorCode.Failure;
    }

    /**
     * @Author: WangKe
     * @Description: 更新出库主记录状态
     * @Date: 2018/3/8 0008
     */
    public ErrorCode updateState(String businessOrder, Integer state, String orgId){
        WarehouseDeliveryDO inboundDO = warehouseDeliveryMapper.findByBusinessOrder(businessOrder, orgId);
        if(inboundDO == null){
            return ErrorCode.IllegalArument;
        }
        inboundDO.setStatus(state);
        return warehouseDeliveryMapper.updateByPrimaryKey(inboundDO)>0?ErrorCode.Success:ErrorCode.Failure;
    }

    /**
     * 根据业务单号修改事务单退货状态
     * @param deliveryNoteDOs List<DeliveryNoteDO> 业务单集合
     * @param status  Integer 退货状态（0未退货，1退货）
     * @return ErrorCode
     */
    public ErrorCode updateReturnStatus(List<DeliveryNoteDO> deliveryNoteDOs,Integer status)
    {
        for(DeliveryNoteDO temp :deliveryNoteDOs)
        {
            warehouseDeliveryMapper.updateReturnStatus(temp.getDeliveryNo(),status);
        }
        return ErrorCode.Success;
    }

    /**
     * @Author: WangKe
     * @Description: 无条码出库时更新事务单状态
     * @Date: 2018/4/4 0004
     */
    public boolean updateStateNoBarcode(String businessOrder, String materialNo, Integer state, String orgId){
        boolean success = warehouseDeliveryMapper.updateStateNoBarcode(state, businessOrder, orgId)>0;
        if(!success){
            return false;
        }
        success = warehouseDeliveryDetailMapper.updateStateNoBarcode(state, businessOrder, materialNo, orgId)>0;
        return success;
    }

    /**
     * 根据零件信息删除出库单详细
     * @param record
     * @return
     */
    public ErrorCode deleteByMaterial(WarehouseDeliveryDetailDO record)
    {
        warehouseDeliveryDetailMapper.deleteByMaterial(record);
        return ErrorCode.Success;
    }

    /**
     * 更新出库单的总数量
     * @param billNo String
     * @param orgId String
     * @return ErrorCode
     */
    public ErrorCode refreshAmount(String billNo,String orgId)
    {
        WarehouseDeliveryDO warehouseDeliveryDO = warehouseDeliveryMapper.findByBusinessOrder(billNo,orgId);

        List<WarehouseDeliveryDetailDO> deliveryDetailDOs =    warehouseDeliveryDetailMapper.findByBusinessOrder(billNo,orgId);

        BigDecimal totalAmount = BigDecimal.ZERO;
        for(WarehouseDeliveryDetailDO tmp:deliveryDetailDOs)
        {
            if(null==tmp)
            {
                continue;
            }
            totalAmount = totalAmount.add(tmp.getAmount());
        }
        warehouseDeliveryDO.setAmount(totalAmount);
        warehouseDeliveryMapper.updateByPrimaryKey(warehouseDeliveryDO);
        return ErrorCode.Success;
    }

    /**
     * @Description: 在新增回购出库单时新增出库事物单
     */
    public boolean saveByBackOutbound(BackInboundAddVO backInboundAddVO, String userId, String orgId) throws Exception{
        if(backInboundAddVO == null || backInboundAddVO.getHeaderInfo() == null || ListUtil.isNullOrEmpty(backInboundAddVO.getMaterialList())){
            return false;
        }
        BackInboundVO backInboundVO = backInboundAddVO.getHeaderInfo();
        List<BackInboundDetailVO> detailVOList = backInboundAddVO.getMaterialList();

        WarehouseDeliveryVO inboundVO = new WarehouseDeliveryVO();
        List<WarehouseDeliveryDetailVO> detailList = new ArrayList<>();
        inboundVO.setBusinessSingle(backInboundVO.getInboundOrder().substring(0, 4));
        inboundVO.setBusinessOrder(backInboundVO.getInboundOrder());
        inboundVO.setWarehouseCode(backInboundVO.getWarehouseCode());
        inboundVO.setInArea(backInboundVO.getInArea());
        inboundVO.setSapInArea(backInboundVO.getSapInArea());
        BigDecimal num = BigDecimal.ZERO;
        WarehouseDeliveryDetailVO detail;
        for(BackInboundDetailVO backInboundDetailVO : detailVOList){
            detail = new WarehouseDeliveryDetailVO();
            detail.setBusinessSingle(inboundVO.getBusinessSingle());
            detail.setBusinessOrder(inboundVO.getBusinessOrder());
            detail.setMaterialNo(backInboundDetailVO.getMaterialsNo());
            detail.setMaterialName(backInboundDetailVO.getMaterialsDes());
            detail.setMaterialType(backInboundDetailVO.getMaterialsType());
            detail.setUnit(backInboundDetailVO.getUnit());
            detail.setAmount(backInboundDetailVO.getAmount());
            detail.setRealAmount(BigDecimal.ZERO);

            num = num.add(backInboundDetailVO.getAmount());
            detailList.add(detail);
        }
        inboundVO.setAmount(num);
        WarehouseDeliveryAddVO inboundAddVO = new WarehouseDeliveryAddVO();
        inboundAddVO.setHeaderInfo(inboundVO);
        inboundAddVO.setDetailList(detailList);

        ErrorCode code = this.add(inboundAddVO, userId, orgId);
        return code.getCode() == 0;
    }
}
